<?php
/**
* file-based storage for QueryTpl objects
*
* This file is part of Webappkit, a packages system for PHP web apps
* @link http://webappkit.net
* @package webappkit
* @subpackage db
* @author J.Ducastel <nospam0@ducastel.name>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
class DbQueryTplStorage extends WakStorage {

    public static $default_cfg=array(
        'storage'=>array(
            'filenames'=>'sql/{{id}}.querytpl.sql')
        ,'criteria'=>array());

    public static function toolFactory($kit,$cfg=array())  {
        return new DbQueryTplStorage($kit,$cfg);
    }

    /*public function has($id) {

    }*/

    /**
     * get query template
     *
     */
    public function get($id) {
        // search file from pattern
        $file=$this->_makeFileName($id); // echo "<p>file = $file</p>";
        if (!$file or !file_exists($this->getPath().$file))
            return false;
        // reading file content
        $content=file_get_contents($this->getPath().$file); // echo $content;
        // building instance
        $instance=new DbQueryTpl($content,$id); // echo $content;
        return $instance;
    }

    /**
     * save query template in clear
     * @param QueryTpl $qtpl
     * @return bool
     */
    public function save(&$qtpl) {
        $id=$qtpl->id;
        $file=$this->getPath().$this->_makeFileName($id); // echo $file;
        $content=$qtpl->getSource();
        $h=fopen($file,'w');
        return fwrite($h,$content);
    }
}
